/* app/containers/App.js */
import React from 'react';
import ReactDom from 'react-dom';
import { connect } from 'react-redux';

import * as Actions from '../actions/detail';
import { bindActionCreators } from 'redux';

import ToolsBar from '../components/ToolsBar';
import Toast from '../components/toast';
import ProductDetail from '../components/ProductDetail';
import MemberList from '../components/MemberList';
import Model from '../components/model';
import Button from '../components/button';

import UserCollect from '../components/detail_module/user_collect';

import FormDialog from './FormDialog';
import AlertDialog from './AlertDialog';
import RuleDialog from './RuleDialog';

import YmtApi from 'YmtApi';

import YmtApiMixin from '../mixins/YmtApiMixin';
import toastMixin from '../mixins/toastMixin';



const hasLogin = YmtApi.utils.hasLogin;

const searchParam = YmtApi.utils.getUrlObj();

const getGroupProduct = function(successFn = ()=>{}){
	const { actions } = this.props;
	const { UserId , AccessToken } = YmtApi.utils.getAuthInfo();

	actions.getProductDetail({ 
		UserId , 
		AccessToken , 
		topicId:searchParam.topicId,
		tuanId:searchParam.tuanId,
		GroupCode:searchParam.groupCode
	},successFn,function(data){
		this.showToast(data.Msg)
	}.bind(this));
}

let Detail = React.createClass({
	mixins:[ toastMixin , YmtApiMixin ],
	getInitialState(){
		console.log('detail init')
		return {
			isLoadIng:true,
			alertDialogShow:false,
			dialogParams:{},
			formDialogShow:false,
			isBindSubmit:false,
			toastShow:false,
			toastTxt:'',
			isRuleShow:false,
			alertMsg:'',
			showButtonList:undefined,
			bindMobileFn:null,
			bindMobileTxt:'',
			showDialogHd:false,
			ruleShow:false,//显示规则
			resetCountDown:false//重置倒计时
		}
	},
	componentDidMount(){
		// this.onShowDialog('formDialogShow');
		// this.setState({
		// 	bindMobileFn:this.onCreateGroupHandler,
		// 	bindMobileTxt:'开团'
		// });
		// 
		// this.onShowDialog('alertDialogShow');
		// 					this.setState({
		// 						alertMsg:'哎呀，手慢了，团已结束了呢',
		// 						showButtonList:[-1],
		// 						showDialogHd:true
		// 					});
		console.log('detail componentDidMount')
		getGroupProduct.call(this,(result,data)=>{
			const {GroupInfo} = data;

			// document.querySelector('#loading').remove();
			var loading = document.getElementById('loading');
			loading.parentNode.removeChild(loading)

			this.setState({
				isLoadIng:false
			})

			YmtApi.isWechat && YmtApi.initWechat({
	           shareConf:{
	               title:GroupInfo.ShareTitle,
	               desc:GroupInfo.ShareDesc,
	               imgUrl:GroupInfo.SharePicUrl,
	               link:location.href.replace(/[&,\?](AccessToken|unionId|openId|wxToken)=[^&#]*/ig, '')
	           }
	       });

		},((result)=>{
			this.showToast(result.Msg)
		}).bind(this));

		YmtApi.on('userStatusChange',((res)=>{
			getGroupProduct.call(this)
		}).bind(this));

	},
	componentWillUnmount(){
		clearInterval(this.timer);
		console.log('detail componentWillUnmount')
	},
	componentWillReceiveProps(nextProps){
		const { groupDetail = {} } = nextProps;
		if( groupDetail.state === 2){
			const { data = {} } = groupDetail,
				  { Status } = data.GroupInfo;

			let hasError = false,
				alertMsg = '',
				showButtonList;
			if(YmtApi.isWechat && !+searchParam.isHistory){
				//如果在这个团中没有相关提示
				if((data.GroupInfo || {}).IsInCurrentTuan){
					switch(Status){
						case 10:
							hasError = true;
							alertMsg ='哎呀，手慢了，团已结束了呢~';
							showButtonList = [4,1]
						break;
					}
				}else{
					switch(Status){
						case 7:
							hasError = true;
							alertMsg ='哎呀，手慢了，团满了，都怪商品那么赞。555~';
							showButtonList = [4,1]
						break;
						case 10:
							hasError = true;
							alertMsg ='哎呀，手慢了，团已结束了呢~';
							showButtonList = [4,1]
						break;
						case 13:
							hasError = true;
							alertMsg ='哎呀，手慢了，团满了<br/>都怪商品那么赞,555~';
							showButtonList = [4,1]
							//未登陆且有wxToken
							if(!this.hasLogin() && searchParam.wxToken){
								showButtonList.push(7);
							}
						break;
					}

				}
			}
			

			if(hasError){
				this.onShowDialog('alertDialogShow');
				this.setState({
					alertMsg,
					showButtonList
				});
			}
		}
	},
	onCreateGroupHandler(){
		const { actions } = this.props;
		const {UserId,AccessToken} = this.getAuthInfo();
		const that = this;
		if(this.hasLogin()){
			actions.createGroup({
				UserId,
				AccessToken,
				TuanId:searchParam.tuanId
			},(result)=>{
				const { Code,Data={} } = result;
				getGroupProduct.call(that);
				if(Code === 200){
					let { Status,StatusText,GroupCode } = Data;
				    //Status =  4
					if(Status === 0){
						this.onShowDialog('alertDialogShow');
						this.onHideDialog('formDialogShow');
						this.setState({
							alertMsg:StatusText,
							showButtonList:[6],
							showDialogHd:true,
							dialogParams:{
								groupCode:GroupCode
							}
						});
					}else if(Status === 15){
						this.setState({
							bindMobileFn:this.onCreateGroupHandler,
							bindMobileTxt:'开团'
						});
						this.onShowDialog('formDialogShow');
					}else{
						let showButtonList;
						if(Status === 2 || Status === 3 || Status === 14){
							showButtonList = [1]
						}else if(Status === 4){
							showButtonList:[9,0]
						}
						this.onShowDialog('alertDialogShow');
						this.setState({
							alertMsg:StatusText,
							showButtonList
						});
					}

				}else if(Code === 201){
					this.showToast(result.Msg || '创团失败');
				}
			},((result)=>{
				this.showToast(result.Msg)
			}).bind(this));
		}else{
			YmtApi.toLogin();
			YmtApi.one('userStatusChange',function(){
				this.onCreateGroupHandler();
				getGroupProduct.call(this);	
			}.bind(this));//执行一次
		}
	},
	onJoinGroupHandler(){
		const { actions } = this.props;
		const {UserId,AccessToken} = this.getAuthInfo();
		const that = this;
		if(this.hasLogin()){
			actions.joinGroup({
				UserId,
				AccessToken,
				TuanId:searchParam.tuanId,
				GroupCode:searchParam.groupCode
			},((data)=>{
				let { Code,Data } = data;
				if(Code === 200 && Data){
					getGroupProduct.call(that);
					let { Status,StatusText } = Data;
					//Status = 3
					if(Status === 0){
						this.onShowDialog('alertDialogShow');
						this.onHideDialog('formDialogShow');
						this.setState({
							alertMsg:StatusText							
						});
						//@WARN 由于存在微信授权之后不登录操作，
						//在绑定手机之后，如果为新用户则会执行sendEvent
						//保存登录态刷新之后需要重新获得再刷新页面
						//否则登录态会丢失
						//window.location.href = YmtApi.utils.addAuth(window.location.href);
					}else if(Status === 1){
						this.setState({
							bindMobileFn:this.onJoinGroupHandler,
							bindMobileTxt:'参团'
						});
						this.onShowDialog('formDialogShow');
					}else{
						let showButtonList ;
						if(Status === 6 ){
							showButtonList = [-1]
						}else if(Status === 3){
							showButtonList = [9,0]
						}else if(Status === 5){
							showButtonList = [4,1]
						}else if(Status === 7){
							showButtonList = [8]
						}else if(Status === 8 
							|| Status === 9
							|| Status === 10
							|| Status === 11){
							showButtonList = [4,1]
						}
						this.onShowDialog('alertDialogShow');
						this.setState({
							alertMsg:StatusText,
							showButtonList
						});
						//setTimeout(location.reload,12E2);
					}
				}else if(Code === 201){
					this.showToast(data.Msg || '参团失败');
				}
			}).bind(this),((data)=>{
				this.showToast(data.Msg)
			}).bind(this));
		}else{
			if(searchParam.wxToken){
				this.setState({
					bindMobileFn:this.onJoinGroupHandler,
					bindMobileTxt:'参团'
				});
				this.onShowDialog('formDialogShow');
			}else{
				YmtApi.toLogin();
				YmtApi.one('userStatusChange',this.onJoinGroupHandler.bind(this));//执行一次
			}
		}
	},
	onShareHandler(shareCfg){
		YmtApi.openShare({
			shareTitle: shareCfg.title,
			shareUrl: shareCfg.url,
			sharePicUrl: shareCfg.pic,
			shareContent: shareCfg.content,
			showWeiboBtn: 0
		})
	},
	onShowDialog(type){
		let obj = {}
		obj[type] = true;
		this.setState(obj);
	},
	onHideDialog(type){
		let obj = {}
		obj[type] = false;
		this.setState(obj);
	},
	onSwitchRuleShowState(){
		this.setState({
			isRuleShow:!this.state.isRuleShow
		})
	},
	onBuyNow(params){
		const {actions} = this.props;
		YmtApi.extends(params,this.getAuthInfo());
		actions.addShoppingCart(params,(()=>{
			// YmtApi.openConfirmOrder({
			//     isNew: true, 
			//     title: '确认订单', 
			//     backType: 1
			// });
			//@TODO暂不支持传参数
			this.openUrl({
				url:`http://preorder.app.ymatou.com/index?ThirdId=${params.ThirdId}`,
				isNew: true, 
				title: '确认订单', 
				backType: 1
			})
		}).bind(this),((result)=>{
			this.showToast(result.Msg || '下单失败.');
		}).bind(this));
	},
	onPayHandler(data){
		YmtApi.openPay({
			isIncludeBonded: data.IsXloboBondedOrder,
			orderId:data.OrderId,
			trandingIds:data.TrandingIds
		});
	},

	render (){ 
		console.log('detail render')
		const { groupDetail={},actions } = this.props;

		let data = YmtApi.extends({
			GroupInfo:{},
			GroupMemberList:[],
			GroupProduct:{},
			GroupSeller:{}
		},groupDetail.data);


		data.GroupProduct.Status = data.GroupInfo.Status;
		data.GroupProduct.SuccessGroupCount = data.GroupInfo.SuccessGroupCount;
		data.GroupProduct.SellerFlag = data.GroupSeller.SellerFlag;
		data.GroupProduct.SellerCountryName = data.GroupSeller.SellerCountryName;
		data.GroupProduct.BeginTime = data.GroupInfo.BeginTime;
		data.GroupProduct.GroupMemberCount = data.GroupInfo.GroupMemberCount;
		//data.GroupProduct.GroupMemberCount =2

		let logisticsInfo = (function(product){
			return (
				<div className="logistics-area">
					{ product.DeliveryMethodId?<span className={'bonded bonded-'+product.DeliveryMethodId}><i className="logistics-icon icon"></i>{product.DeliveryMethodText}</span>:''}
					{ product.CanLocalReturn?<span className="local-return"><i className="logistics-icon icon"></i>本土退货</span>:''}
				</div>
			)
		})(data.GroupProduct);

		let uc = function(){
			if(hasLogin()){
				return (
					<UserCollect userCollect={ {state:groupDetail.state, data:{
						TopicDto :{
							JoinGroupCount:data.JoinGroupCount,
							OpenGroupCount:data.OpenGroupCount
						}
					}} } openUrl={ this.openUrl } hasLogin = { this.hasLogin } isDetail = {true}/>
				)
			}
		}.bind(this)
			// <div className="detail-area">
			// 	<header>
			// 		开团流程
			// 	</header>
			// 	<ul className="group-flow">
			// 		<li className="group-step">
			// 			<div className="dot" data-index="1"></div>
			// 			<div>
			// 				点击底部<br/>
			// 				我要开团
			// 			</div>
			// 		</li>
			// 		<li className="group-step">
			// 			<div className="dot" data-index="2"></div>
			// 			<div>
			// 				邀请三位<br/>
			// 				好友参加
			// 			</div>
			// 		</li>
			// 		<li className="group-step">
			// 			<div className="dot" data-index="3"></div>
			// 			<div>
			// 				到达人数<br/>
			// 				团购成功
			// 			</div>
			// 		</li>
			// 		<li className="group-step">
			// 			<div className="dot" data-index="4"></div>
			// 			<div>
			// 				尽快付款<br/>
			// 				疯抢好货
			// 			</div>
			// 		</li>
			// 	</ul>
			// </div>
			// <div className="detail-area">
			// 	<header>
			// 		参团流程
			// 	</header>
			// 	<ul className="group-flow border-bottom join-step">
			// 		<li className="group-step">
			// 			<div className="dot" data-index="1"></div>
			// 			<div>
			// 				点击底部<br/>
			// 				我要参团
			// 			</div>
			// 		</li>
			// 		<li className="group-step">
			// 			<div className="dot" data-index="2"></div>
			// 			<div>
			// 				分享邀请<br/>
			// 				好友参加
			// 			</div>
			// 		</li>
			// 		<li className="group-step">
			// 			<div className="dot" data-index="3"></div>
			// 			<div>
			// 				到达人数<br/>
			// 				团购成功
			// 			</div>
			// 		</li>
			// 		<li className="group-step">
			// 			<div className="dot" data-index="4"></div>
			// 			<div>
			// 				尽快付款<br/>
			// 				疯抢好货
			// 			</div>
			// 		</li>
			// 	</ul>
			// </div>
		 //    <div className="detail-area">
			// 	<header>
			// 		砍价攻略
			// 	</header>
			// 	<dl className="detail-strategy-list">
			// 		<dt>Q:什么是砍价团？</dt>
			// 		<dd>
			// 			A 找到心仪商品后发起组团，并邀请小伙伴们一起参团，组团成功后即可享受四人成团价。
			// 		</dd>
			// 		<dt>Q:什么是砍价团？</dt>
			// 		<dd>
			// 			A 找到心仪商品后发起组团，并邀请小伙伴们一起参团，组团成功后即可享受四人成团价。
			// 		</dd>
			// 		<dt>Q:什么是砍价团？</dt>
			// 		<dd>
			// 			A 找到心仪商品后发起组团，并邀请小伙伴们一起参团，组团成功后即可享受四人成团价。
			// 		</dd>
			// 	</dl>
			// </div>
			// data.GroupInfo.ActivityPlow
			console.log(data.GroupProduct)
		return (
			<div className="group-detail-container">
				{ uc() }
				<ProductDetail info={ data.GroupProduct } 
					isDetail={true} 
					isMyself={!!+searchParam.isHistory}/>
				<div className="detail-area group-desc">
					{ logisticsInfo }
					{(data.GroupInfo||{}).ProductDesc}
				</div>
				<div dangerouslySetInnerHTML={{__html:data.GroupInfo.ActivityPlow}}/>
				<div className="detail-area">
					<header>
						活动规则
					</header>
					<div className={'detail-rule-content '+(this.state.isRuleShow?'':'mask')} dangerouslySetInnerHTML={{__html:data.GroupInfo.ActivityRule}}/>

					<div className="detail-area-ft detail-rule-footer"
						 onClick = { this.onSwitchRuleShowState }>
						查看更多细则 <i className={'iicon-arrow '+(this.state.isRuleShow?'iicon-arrow-top':'iicon-arrow-bottom')}></i>
					</div>
				</div>
				<div className="detail-area consume-promise"
					  onClick={()=>{
					  	this.openUrl({
					  		url:'http://evt.ymatou.com/activity_4515_capp',
					  		title:'洋码头全球消费保障'
					  	})
					  }}>
					<h3><strong>洋码头全球消费保障 </strong>
						 认真做洋货
						<span className="pull-right">了解详情<i className="iicon-arrow iicon-arrow-right"></i></span>
					</h3>
					<ul className="service-list">
						<li>
							<span className="icon"></span><br/>
							正品保障
						</li>
						<li>
							<span className="icon"></span><br/>
							海外直邮
						</li>
						<li>
							<span className="icon"></span><br/>
							本土客服
						</li>
						<li>
							<span className="icon"></span><br/>
							全球同价
						</li>
					</ul>
				</div>
				<MemberList memberList={data.GroupMemberList} memberCount={data.GroupInfo.Status===10&&!+searchParam.isHistory?0:data.GroupInfo.GroupMemberCount}/>
				<ToolsBar status={data.GroupInfo.Status} 
						  onCreateGroupHandler={this.onCreateGroupHandler}
						  onJoinGroupHandler={this.onJoinGroupHandler}
						  onPayHandler={this.onPayHandler}
						  onShareHandler={ ()=>{
						  	this.onShareHandler({
						  		title:data.GroupInfo.ShareTitle,
						  		content:data.GroupInfo.ShareDesc,
						  		pic:data.GroupInfo.SharePicUrl,
						  		url:`http:\/\/${window.location.host}/detail?groupCode=${data.GroupInfo.GroupCode}&tuanId=${searchParam.tuanId}`
						  	});
						  }}
						 groupInfo={data.GroupInfo}
						 joinGroupCount={this.hasLogin()?data.JoinGroupCount:1}
						 createGroupCount={(this.hasLogin()?data.OpenGroupCount:1)}
						 onBuyNow={this.onBuyNow}
						 productInfo = {
						 	{
						 		SellerId:data.GroupSeller.SellerId,
						 		SellerName:data.GroupSeller.SellerName,
						 		CatalogId:data.GroupProduct.CatalogId
						 	}
						 }
						 updateStatusFn={()=>{
						 	getGroupProduct.call(this)
						 }}
						 isHistory={ !!+searchParam.isHistory}
						 resetCountDown={
						 	this.state.resetCountDown
						 } />
						<AlertDialog 
						     show={this.state.alertDialogShow}
						     params = {this.state.dialogParams}
							 onHideDialog={()=>{
							   	this.onHideDialog('alertDialogShow')
							  }}
							  alertMsg={this.state.alertMsg}
							  showButtonList={this.state.showButtonList}
							  onOpenFormDialog={()=>{
							  	this.setState({
							  		formDialogShow:true
							  	})
							  }}
							  openUrl={this.openUrl}
							  onBuyNow={()=>{
							  	this.onBuyNow({
							  		SellerId:data.GroupSeller.SellerId,
							  		SellerName:data.GroupSeller.SellerName,
							  		CatalogId:data.GroupProduct.CatalogId,
							  		ProductNumber:1,
							  		ThirdId:data.GroupInfo.ThirdId
							  	})
							  }}
							  onShareHandler={
							  	(groupCode)=>{
							  		this.onShareHandler({
							  			title:data.GroupInfo.ShareTitle,
							  			content:data.GroupInfo.ShareDesc,
							  			pic:data.GroupInfo.SharePicUrl,
							  			url:`http:\/\/${window.location.host}/detail?groupCode=${groupCode}&tuanId=${searchParam.tuanId}`
							  		});
							  	}
							  }
							  showDialogHd={
							  	this.state.showDialogHd
							  }
							  onHideFormDialog={
							  	()=>{
							  		this.onHideDialog('formDialogShow')
							  	}
							  }
							  onShowRuleDialog={()=>{
							  	this.setState({
							  		ruleShow:true
							  	})
							  }}
							  resetCountDown= {
							  	()=>{
							  		this.setState({
							  			resetCountDown:true
							  		})
							  	}
							  }/>
						<FormDialog show={this.state.formDialogShow}
							onHideDialog={()=>{
							  	this.onHideDialog('formDialogShow')
							 }}
							actions={actions}
							showToast={this.showToast}
							bindMobileFn = {this.state.bindMobileFn}
							bindMobileTxt = {this.state.bindMobileTxt}
							mobelBinedFn={
								(text,isSwitch)=>{
									this.onShowDialog('alertDialogShow');
									let showButtonList = [2];
									if(YmtApi.isWechat && isSwitch){
										showButtonList.push(5)
									}
									this.setState({
										alertMsg:text,
										showButtonList,
										resetCountDown:true
									});
								}
							} />
				<Toast show={ this.state.toastShow } 
					   message={ this.state.toastTxt }/>
				<RuleDialog show={ this.state.ruleShow } content={data.GroupInfo.ActivityRule} onHideDialog={()=>{
										  	 this.setState({
										  	 	ruleShow:false
										  	 })
										  }}/>
			</div>
		)
	}
});

export default connect(state => (console.log(state),{
		groupDetail:state.groupDetail
	}), dispatch => ({
	actions: bindActionCreators(Actions,dispatch)
}))(Detail);